import { createVNode } from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import request from '@/api/common'
import type { UseEventBusReturn } from '@vueuse/core'

export interface IUseCurd<T> {
  handleDelData: (id: number | number[]) => void;
  handleEditData: (id: number, data: T) => void;
  handleConfirmData: (callback: (...args: []) => any, title?: string) => void;
}

export default function useCurd<T> (baseApi: string, bus?: UseEventBusReturn<string, any>): IUseCurd<T> {
  async function handlePutAction (id: number, data: T) {
    await request.setPath(baseApi).put({ id, ...data })
  }

  async function handleDelAction (id: number | number[]) {
    await request.setPath(baseApi).del([id])
  }

  function handleConfirmData (callback: (...args: []) => any, title = '确定操作吗？') {
    Modal.confirm({
      title,
      icon: createVNode(ExclamationCircleOutlined),
      onOk () {
        callback()
        bus?.emit('ok')
      }
    })
  }

  function handleEditData (id: number, data: T) {
    handleConfirmData(() => handlePutAction(id, data), '确定修改这条数据吗？')
  }

  function handleDelData (id: number | number[]) {
    handleConfirmData(() => handleDelAction(id), '确定删除这条数据吗？')
  }

  return {
    handleDelData,
    handleEditData,
    handleConfirmData
  }
}
